跳到主要内容

throttle and debounce

函数防抖(debounce):当持续触发事件时,一定时间段内没有再触发事件,事件处理函数才会执行一次,如果设定的时间到来之前,又一次触发了事件,就重新开始延时。

function debounce(fn, wait) {
var timeout = null;
return function () {
if (timeout !== null) clearTimeout(timeout);
timeout = setTimeout(fn, wait);
};
}
// 处理函数
function handle() {
console.log(Math.random());
}
// 滚动事件
window.addEventListener('scroll', debounce(handle, 1000));

函数节流(throttle):当持续触发事件时,保证一定时间段内只调用一次事件处理函数。

var throttle = function (func, delay) {
var prev = Date.now();
return function () {
var context = this;
var args = arguments;
var now = Date.now();
if (now - prev >= delay) {
func.apply(context, args);
prev = Date.now();
}
};
};
function handle() {
console.log(Math.random());
}
window.addEventListener('scroll', throttle(handle, 1000));
var throttle = function (func, delay) {
var timer = null;
var startTime = Date.now();
return function () {
var curTime = Date.now();
var remaining = delay - (curTime - startTime);
var context = this;
var args = arguments;
clearTimeout(timer);
if (remaining <= 0) {
func.apply(context, args);
startTime = Date.now();
} else {
timer = setTimeout(func, remaining);
}
};
};
function handle() {
console.log(Math.random());
}
window.addEventListener('scroll', throttle(handle, 1000));

https://mp.weixin.qq.com/s/Vkshf-nEDwo2ODUJhxgzVA